﻿/*----------------------------------------------------------------
//  <copyright file="JsonNoFoundHandlerMiddleware.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2022-11-15 11:01</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.AspNetCore
{
    #region "Json前端技术404返回index.html中间件"
    /// <summary>
    /// Json前端技术404返回index.html中间件
    /// </summary>
    public class JsonNoFoundHandlerMiddleware : IMiddleware
    {
        //字段
        private readonly RequestDelegate _next;

        #region "构造函数"
        #region "初始化一个<see cref="JsonNoFoundHandlerMiddleware"/>类型的新实例"
        /// <summary>
        /// 初始化一个<see cref="JsonNoFoundHandlerMiddleware"/>类型的新实例
        /// </summary>
        /// <param name="next"></param>
        public JsonNoFoundHandlerMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        #endregion

        #endregion

        #region "方法"
        #region "执行中间件拦截逻辑"
        /// <summary>
        /// 执行中间件拦截逻辑
        /// </summary>
        /// <param name="context">Http上下文</param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            await _next(context);
            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)
                && !context.Request.Path.Value.StartsWith("/api/", StringComparison.OrdinalIgnoreCase))
            {
                context.Request.Path = "/index.html";
                await _next(context);
            }
        }
        #endregion

        #endregion

    }
    #endregion

}
